package cn.itcast.web.action;

import cn.itcast.crm.domain.Customer;
import cn.itcast.domain.constant.Constants;
import cn.itcast.utils.MailUtils;
import cn.itcast.web.action.common.BaseAction;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import javax.jms.*;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
   //注入队列模板对象
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private Queue queue;
    //customer_sendSms.action 发送短信验证码
    @Action(value = "customer_sendSms")
    public String sendSms() {
        final String randomCode = RandomStringUtils.randomNumeric(6);
        //将验证码存入session
        ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
        System.out.println(randomCode);
        //发送短信  使用消息队列
//        jmsQueueTemplate.send("bos_sms",new MessageCreator() {
//            @Override
//            public Message createMessage(Session session) throws JMSException {
//                MapMessage mapMessage = session.createMapMessage();
//                mapMessage.setString("telephone",model.getTelephone());
//                mapMessage.setString("randomCode",randomCode);
//
//                return mapMessage;
//            }
//        });
        jmsTemplate.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone",model.getTelephone());
                mapMessage.setString("randomCode",randomCode);
                return mapMessage;
            }
        });
        /*try {
            String msg = MsgUtils.sendMsg(model.getTelephone(), randomCode);
            System.out.println(msg);//success 短信成功发送 fail短信发送失败
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
        return NONE;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;//注入spring data redis 模板对象
    private String checkCode;//短信验证码

    public void setCheckCode(String checkCode) {
        this.checkCode = checkCode;
    }

    //  customer_regist.action 注册
    @Action(value = "customer_regist", results = {@Result(name = "success", location = "signup-success.html", type = "redirect"),
            @Result(name = "input", location = "signup.html", type = "redirect")})
    public String regist() {
        String code = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
        //对验证码进行非空判断
        if (StringUtils.isBlank(checkCode) || StringUtils.isBlank(code)) {
            return INPUT;
        }
        //对验证码进行匹配判断
        else if (!checkCode.equals(code)) {
            return INPUT;
        }
        //验证码匹配成功 清除session中的验证码
        ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), null);
        //验证通过,将注册信息存入数据库 crm系统
        WebClient.create("http://localhost:8085/services/customerService/customer").type(MediaType.APPLICATION_JSON)
                .post(model);
        //编辑信息 发送激活邮件
        String activeCode = RandomStringUtils.randomNumeric(32);//生成激活
        //将激活码存入redis key:telephone value:activecode 有效时间 1 小时
        redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 1, TimeUnit.HOURS);
        //编辑短信内容
        String content = "尊敬的客户，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
                + MailUtils.activeUrl + "?telephone=" + model.getTelephone()
                + "&activecode=" + activeCode + "'>速运快递邮箱绑定地址</a>";
        ;
        /*
          subject:邮件标题
          content :邮件文本内容
          to:目标地址
          activeCode:激活码
         */
     /*   MailUtils.sendMail("激活邮件", content, model.getEmail(), activeCode);*/
        return SUCCESS;

    }

    //邮箱激活 参数 telephone activeCode
    private String activeCode;

    public void setActiveCode(String activeCode) {
        this.activeCode = activeCode;
    }

    @Action(value = "customer_activeMail")
    public String activeMail() {
        ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
        //邮箱激活主要逻辑:和缓存中相对应的激活码进行匹配 然后对type属性进行更改
        String redisCode = redisTemplate.opsForValue().get(model.getTelephone());
        //判断激活码是否失效
        if (redisCode == null || !activeCode.equals(redisCode)) {
            //激活码失效
            try {
                ServletActionContext.getResponse().getWriter().write("激活码失效,请重新登录");
                return NONE;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //激活码可用 防止重复激活 先根据telephone查询 未激活则激活 已激活则直接返回已激活 还需要防止激活码重复激活
        Customer customer = WebClient.create(Constants.CRM_HOST+Constants.CRM_URL+"/services/customerService/findbytelephone/" + model.getTelephone())
                .type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(Customer.class);
        //账号已激活
        if (1 == customer.getType()) {
            //清除缓存中数据 防止重复激活
            redisTemplate.delete(model.getTelephone());
            try {
                ServletActionContext.getResponse().getWriter().write("账号已经激活");
                return NONE;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //账号未激活 激活账号
        WebClient.create("http://localhost:8085/sms/services/customerService/updatetype/" + model.getTelephone())
                .type(MediaType.APPLICATION_JSON).get();
        //清除缓存中数据 防止重复激活
        redisTemplate.delete(model.getTelephone());
        try {
            ServletActionContext.getResponse().getWriter().write("账号激活成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NONE;
    }
    //用户登录
    // action="customer_login.action
    @Action(value="customer_login",results = {@Result(name = "login",location = "login.html",type = "redirect"),
                                              @Result(name="success",location = "#/myhome",type = "redirect")})
    public String login(){
        Customer customer = WebClient.create(Constants.CRM_HOST + Constants.CRM_URL + "/services/customerService/login/" + model.getTelephone() + "/" + model.getPassword())
                .accept(MediaType.APPLICATION_JSON).get(Customer.class);
        //登录失败 return login 重新登录
        if(customer==null){
            return LOGIN;
        }
        //登录成功 return success 将customer 存入session
        ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
        return SUCCESS;
    }
}
